package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    private ClazzService clazzService;
    /**
     * 分页条件查询学员信息
     *
     * @param student
     * @return
     */
    @Override
    public PageResult<Student> listStudent(StudentQueryParam student) {
        //分页查询学员基本信息
        Page<Student> page =new Page<>(student.getPage(),student.getPageSize());
        page.addOrder(OrderItem.desc("update_time"));
        page = lambdaQuery().like(student.getName() !=null && !student.getName().isEmpty(),Student::getName,student.getName())
                .eq(student.getDegree()!=null,Student::getDegree,student.getDegree())
                .eq(student.getClazzId()!=null,Student::getClazzId,student.getClazzId())
                .page(page);
        //查询学员的班级信息   多表查询
        List<Student> students = page.getRecords();
        List<Integer> clazzIds = students.stream().map(student1 -> student1.getId()).collect(Collectors.toList());
        if(clazzIds!=null && !clazzIds.isEmpty()){
            students.forEach(student1 -> {
                List<Clazz> clazzs = clazzService.list(new LambdaQueryWrapper<Clazz>().eq(Clazz::getId, student1.getClazzId()));
                clazzs.forEach(clazz -> {
                    if(student1.getClazzId()!=null && student1.getClazzId().equals(clazz.getId())){
                        student1.setClazzName(clazz.getName());
                    }
                });
            });
        }
        return new PageResult<>(page.getTotal(),students);
    }

    /**
     * 违纪扣分
     *
     * @param id
     * @param score
     */
    @Override
    public void violation(Integer id, Integer score) {
        UpdateWrapper<Student> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id)
                .setSql("violation_score=violation_score+"+score)
                .setSql("violation_count=violation_count+1");
        update(updateWrapper);
    }

}
